package com.lanou.dllo.soccernews.fragment.circlefragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.dllo.soccernews.R;
import com.lanou.dllo.soccernews.adapter.CircleViewAdapte;
import com.lanou.dllo.soccernews.bean.CircleArticlesEntity;
import com.lanou.dllo.soccernews.bean.CircleBean;
import com.lanou.dllo.soccernews.bean.greendao.ArticlesEntity;
import com.lanou.dllo.soccernews.detailActivty.DetailCirclePageActivity;
import com.lanou.dllo.soccernews.detailActivty.DetailRecommendPageActivity;
import com.lanou.dllo.soccernews.utils.CircleOnClickListener;
import com.lanou.dllo.soccernews.utils.MyItemOnClickListener;
import com.lanou.dllo.soccernews.view.DividerItemDecoration;
import com.lanou.dllo.soccernews.volley.VolleySingleton;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/24.
 */
public class CircleFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView circleRecycleview;
    private CircleViewAdapte circleViewAdapte;
    private VolleySingleton volleySingleton;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private LinearLayoutManager lm;
    private int lastVisibleItem;
    String url = "https://api.dongqiudi.com/tabs_static/2/iphone/66.json";
    String nextUrl = null;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_circle, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        circleRecycleview = (RecyclerView) view.findViewById(R.id.circle_rcview);

        circleViewAdapte = new CircleViewAdapte();
        volleySingleton = VolleySingleton.getInstance();

        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);

    }

    //https://api.dongqiudi.com/tabs/2/android/66.json?after=2
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        getFromIntenetData(url);

        //变换颜色
        mSwipeRefreshLayout.setColorSchemeResources(R.color.darkorange, R.color.aqua,
                R.color.bisque, R.color.burlywood);
        //   mSwipeRefreshLayout.setProgressBackgroundColor(R.color.yellow);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        // 这句话是为了，第一次进入页面的时候显示加载进度条与下拉的位置
        mSwipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));


        circleRecycleview.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,
                                             int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == circleViewAdapte.getItemCount()) {
                    //  mSwipeRefreshLayout.setRefreshing(true);
                    // 此处在现实项目中，请换成网络请求数据代码，sendRequest .....

                    onLoad();


                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = lm.findLastVisibleItemPosition();
            }

        });
        circleRecycleview.setHasFixedSize(true);
        lm = new LinearLayoutManager(getContext());
        lm.setOrientation(LinearLayoutManager.VERTICAL);
        circleRecycleview.addItemDecoration(new
                DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        circleRecycleview.setLayoutManager(lm);
        circleRecycleview.setAdapter(circleViewAdapte);

        //加载数据

        circleViewAdapte.setOnCircleOnClickListener(new CircleOnClickListener() {
            @Override
            public void onItemClickCircle(CircleArticlesEntity circleArticlesEntity) {
                Intent intent = new Intent(getActivity(), DetailCirclePageActivity.class);

                intent.putExtra("id", circleArticlesEntity.getId());
                Log.i("lanou00",circleArticlesEntity.getId()+"llllll");
                startActivity(intent);
            }
        });
    }

    private void onLoad() {
        isRefresh = false;
//        getFromIntenetData(nextUrl);
//
//        mSwipeRefreshLayout.setRefreshing(false);

        handler.sendEmptyMessageDelayed(0, 3000);
    }

    @Override
    public void onRefresh() {
        //  isRefresh = true;

//        getFromIntenetData(url);//获取网络数据
//
//
//
//        mSwipeRefreshLayout.setRefreshing(false);

        handler.sendEmptyMessageDelayed(1, 3000);
    }

    private boolean isRefresh = true;

    private void getFromIntenetData(String url) {
        StringRequest request = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        CircleBean circle = gson.fromJson(response, CircleBean.class);
                        nextUrl = circle.getNext();
                        if (circle != null) {
                            List<CircleArticlesEntity> articles = circle.getArticles();
                            if (articles != null && articles.size() > 0) {
                                if (isRefresh) {
                                    circleViewAdapte.addRefreshData(articles);
                                } else {
                                    circleViewAdapte.addLoadData(articles);
                                }
                            }

                        }

                    }
                }, new Response.ErrorListener() {


            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                // TODO Auto-generated method stub
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        volleySingleton.addRequest(request);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://上拉加载


                    onLoad();

                    getFromIntenetData(nextUrl);
                    mSwipeRefreshLayout.setRefreshing(false);

                    break;

                case 1:
                    mSwipeRefreshLayout.setRefreshing(false);
                    onRefresh();
                    getFromIntenetData(url);


                    break;
            }
        }
    };

}
